<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="(value) => emit('update:visible', value)"
    :title="isView ? '查看工单' : (formData ? '编辑工单' : '新增工单')"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      :disabled="isView"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单编号" prop="ticketNo">
            <el-input v-model="form.ticketNo" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入工单标题" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="问题类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择问题类型" style="width: 100%">
              <el-option label="设备故障" value="equipment-fault" />
              <el-option label="系统异常" value="system-error" />
              <el-option label="数据异常" value="data-error" />
              <el-option label="网络问题" value="network-issue" />
              <el-option label="其他问题" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报告人" prop="reporter">
            <el-input v-model="form.reporter" placeholder="请输入报告人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-input v-model="form.department" placeholder="请输入所属部门" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="处理人" prop="assignee">
            <el-input v-model="form.assignee" placeholder="请输入处理人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择工单状态" style="width: 100%">
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              placeholder="请选择创建时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="更新时间" prop="updateTime">
            <el-date-picker
              v-model="form.updateTime"
              type="datetime"
              placeholder="请选择更新时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="问题描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请详细描述问题现象和影响"
        />
      </el-form-item>

      <el-form-item label="解决方案" prop="solution">
        <el-input
          v-model="form.solution"
          type="textarea"
          :rows="3"
          placeholder="请输入解决方案或处理步骤"
        />
      </el-form-item>

      <el-form-item label="处理结果" prop="result">
        <el-input
          v-model="form.result"
          type="textarea"
          :rows="3"
          placeholder="请输入处理结果"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  formData?: any
  isView?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: null,
  isView: false
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  id: null,
  ticketNo: '',
  title: '',
  type: '',
  priority: 'medium',
  reporter: '',
  phone: '',
  email: '',
  department: '',
  assignee: '',
  status: 'pending',
  createTime: '',
  updateTime: '',
  description: '',
  solution: '',
  result: '',
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择问题类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  reporter: [
    { required: true, message: '请输入报告人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属部门', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择工单状态', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' }
  ]
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 初始化表单
const initForm = () => {
  if (props.formData) {
    Object.assign(form, props.formData)
  } else {
    // 重置表单
    Object.assign(form, {
      id: null,
      ticketNo: generateTicketNo(),
      title: '',
      type: '',
      priority: 'medium',
      reporter: '',
      phone: '',
      email: '',
      department: '',
      assignee: '',
      status: 'pending',
      createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      updateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      description: '',
      solution: '',
      result: '',
      remark: ''
    })
  }
  
  // 清除验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 生成工单编号
const generateTicketNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `PT${year}${month}${day}${random}`
}

// 模拟API - 保存工单
const saveProblemTicket = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success(data.id ? '更新成功' : '创建成功')
    return true
  } catch (error) {
    ElMessage.error(data.id ? '更新失败' : '创建失败')
    return false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  const success = await saveProblemTicket(form)
  if (success) {
    emit('success')
    handleClose()
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>